<template>
  <div class="bzhh-container">
    <div class="banner-background"></div>
    <div class="content-wrapper">
      <div class="page-title">
        <h2>八字精批</h2>
        <div class="title-decoration">
          <span class="decoration-line"></span>
          <span class="heart-icon">❤</span>
          <span class="decoration-line"></span>
        </div>
        <p class="subtitle">深入解析人生格局与命运</p>
      </div>

      <div class="couple-info">
        <div class="person-info male-info">
          <div class="info-title">
            <i class="male-icon">♂</i>
            <h3>受测者信息</h3>
          </div>
          <div class="form-group">
            <label class="block text-sm text-gray-700">姓名</label>
            <input v-model="malename" class="mt-1 block w-full border rounded px-3 py-2" placeholder="姓名（可选）" />
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">日期类型</label>
            <div class="mt-1 flex items-center space-x-4">
              <label class="inline-flex items-center"><input type="radio" value="solar" v-model="maleDateTime" class="mr-2" /> 阳历</label>
              <label class="inline-flex items-center"><input type="radio" value="lunar" v-model="maleDateTime" class="mr-2" /> 农历</label>
            </div>
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">出生日期</label>
            <input type="date" v-model="maleDate" class="mt-1 block w-full border rounded px-3 py-2" @change="handleMaleDateChange" />
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">时辰</label>
            <select v-model="maleTimeIndex" class="mt-1 block w-full border rounded px-3 py-2" @change="calculateBazi">
              <option v-for="opt in timeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <div class="flex items-center space-x-4 mt-3">
            <div>
              <label class="block text-sm text-gray-700">性别</label>
              <div class="mt-1 flex items-center space-x-3">
                <label class="inline-flex items-center"><input type="radio" value="male" v-model="maleGender" class="mr-2"/> 男</label>
                <label class="inline-flex items-center"><input type="radio" value="female" v-model="maleGender" class="mr-2"/> 女</label>
              </div>
            </div>
            <div v-if="maleDateTime === 'lunar'" class="flex items-center">
              <label class="inline-flex items-center"><input type="checkbox" v-model="maleIsLeapMonth" class="mr-2" /> 闰月</label>
            </div>
          </div>
        </div>

        <div class="person-info female-info">
          <div class="info-title">
            <i class="female-icon">♀</i>
            <h3>（可选）参考者信息</h3>
          </div>

          <div class="form-group">
            <label class="block text-sm text-gray-700">姓名</label>
            <input v-model="femalename" class="mt-1 block w-full border rounded px-3 py-2" placeholder="姓名（可选）" />
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">日期类型</label>
            <div class="mt-1 flex items-center space-x-4">
              <label class="inline-flex items-center"><input type="radio" value="solar" v-model="femaleDateTime" class="mr-2" /> 阳历</label>
              <label class="inline-flex items-center"><input type="radio" value="lunar" v-model="femaleDateTime" class="mr-2" /> 农历</label>
            </div>
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">出生日期</label>
            <input type="date" v-model="femaleDate" class="mt-1 block w-full border rounded px-3 py-2" @change="handleFemaleDateChange" />
          </div>

          <div class="form-group mt-3">
            <label class="block text-sm text-gray-700">时辰</label>
            <select v-model="femaleTimeIndex" class="mt-1 block w-full border rounded px-3 py-2" @change="calculateBazi2">
              <option v-for="opt in timeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <div class="flex items-center space-x-4 mt-3">
            <div>
              <label class="block text-sm text-gray-700">性别</label>
              <div class="mt-1 flex items-center space-x-3">
                <label class="inline-flex items-center"><input type="radio" value="male" v-model="femaleGender" class="mr-2"/> 男</label>
                <label class="inline-flex items-center"><input type="radio" value="female" v-model="femaleGender" class="mr-2"/> 女</label>
              </div>
            </div>
            <div v-if="femaleDateTime === 'lunar'" class="flex items-center">
              <label class="inline-flex items-center"><input type="checkbox" v-model="femaleIsLeapMonth" class="mr-2" /> 闰月</label>
            </div>
          </div>
        </div>
      </div>

      <div class="mt-4">
        <button @click="generateDetailedReport" :disabled="loading" class="generate-btn inline-flex items-center px-4 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded">
          <i class="match-icon mr-2">✦</i>
          <span v-if="!loading">开始生成精批</span>
          <span v-else>生成中...</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
definePageMeta({ middleware: 'admin-access' })
import Lunisolar from 'lunisolar';

export default {
  name: 'BzjpPage',
  components: {},
  data() {
    return {
      malename: '',
      maleDateTime: 'solar',
      maleDate: '',
      maleTimeIndex: '0',
      maleGender: 'male',
      maleIsLeapMonth: false,
      baziInfo: null,
      showBaziInfo: false,
      baziStr: '',
      timeOptions: [
        { label: '早子时 (00:00-1:00)', value: '0' },
        { label: '丑时 (1:00-3:00)', value: '1' },
        { label: '寅时 (3:00-5:00)', value: '2' },
        { label: '卯时 (5:00-7:00)', value: '3' },
        { label: '辰时 (7:00-9:00)', value: '4' },
        { label: '巳时 (9:00-11:00)', value: '5' },
        { label: '午时 (11:00-13:00)', value: '6' },
        { label: '未时 (13:00-15:00)', value: '7' },
        { label: '申时 (15:00-17:00)', value: '8' },
        { label: '酉时 (17:00-19:00)', value: '9' },
        { label: '戌时 (19:00-21:00)', value: '10' },
        { label: '亥时 (21:00-23:00)', value: '11' },
        { label: '晚子时 (23:00-00:00)', value: '12' }
      ],
      femalename: '',
      femaleDateTime: 'solar',
      femaleDate: '',
      femaleTimeIndex: '0',
      femaleGender: 'female',
      femaleIsLeapMonth: false,
      baziInfo2: null,
      showBaziInfo2: false,
      baziStr2: '',
      loading: false,
    };
  },
  methods: {
    handleMaleDateTypeChange() {
      this.maleDate = '';
    },
    handleMaleDateChange() {
      this.maleIsLeapMonth = false;
      this.calculateBazi();
    },
    handleFemaleDateTypeChange() {
      this.femaleDate = '';
    },
    handleFemaleDateChange() {
      this.femaleIsLeapMonth = false;
      this.calculateBazi2();
    },
    getBaziStr() {
      if (this.baziInfo && this.baziInfo.char8) {
        this.baziStr = ', 八字：' + this.baziInfo.char8.year.name + ' ' + this.baziInfo.char8.month.name + ' ' + this.baziInfo.char8.day.name + ' ' + this.baziInfo.char8.hour.name;
      } else {
        this.baziStr = '';
      }
    },
    calculateBazi() {
      if (!this.maleDate || this.maleTimeIndex === undefined) {
        this.showBaziInfo = false;
        return;
      }

      try {
        let date;
        let timeStr = '';
        if (this.maleDateTime === 'solar') {
          if (!/^\d{4}-\d{2}-\d{2}$/.test(this.maleDate)) {
            alert('阳历日期格式不正确，请使用YYYY-MM-DD格式');
            return;
          }
        } else {
          if (!/^\d{4}-\d{1,2}-\d{1,2}$/.test(this.maleDate)) {
            alert('农历日期格式不正确，请使用YYYY-MM-DD格式');
            return;
          }
        }

        switch (this.maleTimeIndex) {
          case '0': timeStr = '00:30'; break;
          case '1': timeStr = '02:00'; break;
          case '2': timeStr = '04:00'; break;
          case '3': timeStr = '06:00'; break;
          case '4': timeStr = '08:00'; break;
          case '5': timeStr = '10:00'; break;
          case '6': timeStr = '12:00'; break;
          case '7': timeStr = '14:00'; break;
          case '8': timeStr = '16:00'; break;
          case '9': timeStr = '18:00'; break;
          case '10': timeStr = '20:00'; break;
          case '11': timeStr = '22:00'; break;
          case '12': timeStr = '23:30'; break;
          default: timeStr = '12:00:00'; break;
        }

        if (this.maleDateTime === 'solar') {
          date = new Lunisolar(`${this.maleDate} ${timeStr}`);
          this.baziInfo = date;
          this.getBaziStr();
        } else {
          const dateParts = this.maleDate.split('-');
          const year = parseInt(dateParts[0]);
          let month = parseInt(dateParts[1]);
          const day = parseInt(dateParts[2]);
          const lunarData = {
            year: year,
            month: this.maleIsLeapMonth ? month + 100 : month,
            day: day,
            hour: parseInt(this.maleTimeIndex),
          };
          date = Lunisolar.fromLunar(lunarData);
          this.baziInfo = date;
          this.getBaziStr();
        }

        this.showBaziInfo = !!this.baziInfo;
      } catch (error) {
        console.error('计算八字信息时出错:', error);
        this.showBaziInfo = false;
      }
    },
    getBaziStr2() {
      if (this.baziInfo2 && this.baziInfo2.char8) {
        this.baziStr2 = ', 八字：' + this.baziInfo2.char8.year.name + ' ' + this.baziInfo2.char8.month.name + ' ' + this.baziInfo2.char8.day.name + ' ' + this.baziInfo2.char8.hour.name;
      } else {
        this.baziStr2 = '';
      }
    },
    calculateBazi2() {
      if (!this.femaleDate || this.femaleTimeIndex === undefined) {
        this.showBaziInfo2 = false;
        return;
      }

      try {
        let date;
        let timeStr = '';
        if (this.femaleDateTime === 'solar') {
          if (!/^\d{4}-\d{2}-\d{2}$/.test(this.femaleDate)) {
            alert('阳历日期格式不正确，请使用YYYY-MM-DD格式');
            return;
          }
        } else {
          if (!/^\d{4}-\d{1,2}-\d{1,2}$/.test(this.femaleDate)) {
            alert('农历日期格式不正确，请使用YYYY-MM-DD格式');
            return;
          }
        }

        switch (this.femaleTimeIndex) {
          case '0': timeStr = '00:30'; break;
          case '1': timeStr = '02:00'; break;
          case '2': timeStr = '04:00'; break;
          case '3': timeStr = '06:00'; break;
          case '4': timeStr = '08:00'; break;
          case '5': timeStr = '10:00'; break;
          case '6': timeStr = '12:00'; break;
          case '7': timeStr = '14:00'; break;
          case '8': timeStr = '16:00'; break;
          case '9': timeStr = '18:00'; break;
          case '10': timeStr = '20:00'; break;
          case '11': timeStr = '22:00'; break;
          case '12': timeStr = '23:30'; break;
          default: timeStr = '12:00:00'; break;
        }

        if (this.femaleDateTime === 'solar') {
          date = new Lunisolar(`${this.femaleDate} ${timeStr}`);
          this.baziInfo2 = date;
          this.getBaziStr2();
        } else {
          const dateParts = this.femaleDate.split('-');
          const year = parseInt(dateParts[0]);
          let month = parseInt(dateParts[1]);
          const day = parseInt(dateParts[2]);
          const lunarData = {
            year: year,
            month: this.femaleIsLeapMonth ? month + 100 : month,
            day: day,
            hour: parseInt(this.femaleTimeIndex),
          };
          date = Lunisolar.fromLunar(lunarData);
          this.baziInfo2 = date;
          this.getBaziStr2();
        }

        this.showBaziInfo2 = !!this.baziInfo2;
      } catch (error) {
        console.error('计算八字信息时出错:', error);
        this.showBaziInfo2 = false;
      }
    },
    async generateDetailedReport() {
      if (!this.maleDate) {
        alert('请选择出生日期');
        return;
      }

      this.loading = true;

      try {
        const timeLabel = (index) => {
          switch (index) {
            case '0': return '早子时 (00:00-1:00)';
            case '1': return '丑时 (1:00-3:00)';
            case '2': return '寅时 (3:00-5:00)';
            case '3': return '卯时 (5:00-7:00)';
            case '4': return '辰时 (7:00-9:00)';
            case '5': return '巳时 (9:00-11:00)';
            case '6': return '午时 (11:00-13:00)';
            case '7': return '未时 (13:00-15:00)';
            case '8': return '申时 (15:00-17:00)';
            case '9': return '酉时 (17:00-19:00)';
            case '10': return '戌时 (19:00-21:00)';
            case '11': return '亥时 (21:00-23:00)';
            case '12': return '晚子时 (23:00-00:00)';
            default: return '未知时辰';
          }
        };

        let msg = '请为下列个人提供详细的八字精批（命局格局、喜用神、性格倾向、事业财富、婚姻家庭、健康与大运建议等），信息如下：';
        msg += '\n姓名:' + this.malename + ', 日期类型:' + (this.maleDateTime === 'solar' ? '阳历' : '农历') + ', 出生:' + this.maleDate + ', 时辰:' + timeLabel(this.maleTimeIndex) + ', 性别:' + (this.maleGender === 'male' ? '男' : '女');
        if (this.maleDateTime === 'lunar' && this.maleIsLeapMonth) msg += ', 闰月:是';
        msg += this.baziStr;

        if (this.femaleDate) {
          msg += '\n（参考）姓名:' + this.femalename + ', 日期类型:' + (this.femaleDateTime === 'solar' ? '阳历' : '农历') + ', 出生:' + this.femaleDate + ', 时辰:' + timeLabel(this.femaleTimeIndex) + ', 性别:' + (this.femaleGender === 'male' ? '男' : '女');
          if (this.femaleDateTime === 'lunar' && this.femaleIsLeapMonth) msg += ', 闰月:是';
          msg += this.baziStr2;
        }

        // 保存描述并跳转到聊天页用于生成详细精批
        import('@/lin/util/data-transfer').then(({ saveData, generateUniqueId }) => {
          const id = generateUniqueId();
          const ok = saveData(id, msg);
          if (ok) {
            window.open(`/ai-tools/chat?data_id=${id}`);
          } else {
            alert('保存数据失败');
          }
        }).catch(e => {
          console.error(e);
          try {
            const encoded = encodeURIComponent(msg);
            window.open(`/ai-tools/chat?user_input=${encoded}`);
          } catch (err) {
            alert('跳转到聊天页失败');
          }
        });
      } catch (error) {
        console.error(error);
        alert('生成精批时出错');
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.bzhh-container {
  padding: 24px;
}
.banner-background {
  height: 120px;
  background: linear-gradient(90deg, #ffd6e0, #fff1f3);
  border-radius: 8px;
  margin-bottom: 16px;
}
.content-wrapper {
  max-width: 900px;
  margin: -60px auto 0;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.06);
}
.page-title h2 { margin: 0; }
.title-decoration { display:flex; align-items:center; gap:8px; margin-top:8px }
.decoration-line { flex:1; height:1px; background:#eee }
.heart-icon { color:#ff6b81 }
.subtitle { color:#888; margin-top:8px }
.couple-info { display:flex; gap:16px; margin-top:18px }
.person-info { flex:1; background:#fafafa; padding:12px; border-radius:8px }
.info-title { display:flex; align-items:center; gap:8px }
.male-icon { color:#3b82f6 }
.female-icon { color:#f472b6 }
.generate-btn { margin-top:18px }
</style>